/**
 * 项目名：化工企业安全生产信息化管理平台
 * 日期：    2020-03-17 14:00:29
 * Copyright (c) 2015- -版权所有
 */

package com.joysuch.wwyt.edu.controller;

import cn.zlg.common.springmvc.validate.constraints.NotNull;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.common.util.PageDataUtils;
import com.joysuch.wwyt.core.exception.ApiBusinessException;
import com.joysuch.wwyt.edu.bean.*;
import com.joysuch.wwyt.edu.bean.EduTrainningRecordListBean.SearchEduTrainningRecord;
import com.joysuch.wwyt.edu.entity.EduTrainningRecord;
import com.joysuch.wwyt.edu.entity.EduTrainningRecordUser;
import com.joysuch.wwyt.edu.service.EduTrainningRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.xml.crypto.Data;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/edu/trainning-record")
@Api(tags = "教育-培训记录")
public class EduTrainningRecordController {

    private static final Logger logger = LoggerFactory.getLogger(EduTrainningRecordController.class);

    @Autowired
    private EduTrainningRecordService eduTrainningRecordService;

    @RequiresPermissions("edu:trainning:record:add")
    @RequestMapping("add")
    public Object add(@Valid @RequestBody EduTrainningRecordEditBean entity) {
        eduTrainningRecordService.add(entity);
        return ResultBean.success("");
    }

    @RequiresPermissions("edu:trainning:record:update")
    @RequestMapping("update")
    public Object update(@Valid @RequestBody EduTrainningRecordEditBean entity) {
        if (entity.getId() == null) {
            return ResultBean.fail(102, "未指定主键");
        }
        eduTrainningRecordService.update(entity);
        return ResultBean.success("");
    }

    //  @RequiresPermissions("edu:trainning:record")
    @RequestMapping("page")
    public Object page(Pageable page, SearchEduTrainningRecord condition) {
        page = PageDataUtils.addOrderByDesc(page, "id");
        Page<EduTrainningRecordListBean> data = eduTrainningRecordService.findByPage(page, condition);
        return ResultBean.pageData(data.getContent(), data.getTotalElements());
    }

    //  @RequiresPermissions("edu:trainning:record")
    @RequestMapping("select-page")
    public Object selectPage(Pageable page, SearchEduTrainningRecord condition) {
        page = PageDataUtils.addOrderByDesc(page, "id");
        Page<EduTrainningRecordListBean> data = eduTrainningRecordService.findByPage(page, condition);
        return ResultBean.pageData(data.getContent(), data.getTotalElements());
    }

    @RequiresPermissions("edu:trainning:record:delete")
    @RequestMapping("delete")
    public Object delete(Long id) throws Exception {
        eduTrainningRecordService.delete(id);
        return ResultBean.success("");
    }

    //  @RequiresPermissions("edu:trainning:record")
    @RequestMapping("get")
    public Object getById(Long id) {
        return ResultBean.success(eduTrainningRecordService.getById(id));
    }

    @ApiOperation(value = "培训活动列表")
    @GetMapping("trainningRecordList")
    public Object trainningRecordList(SearchEduTrainningRecord condition) {
        return eduTrainningRecordService.trainningRecordList(condition);
    }

    @ApiOperation(value = "培训活动发布或取消")
    @GetMapping("publishOrUnPublish")
    public Object trainningPublish(SearchEduTrainningRecord condition) throws ApiBusinessException {
        eduTrainningRecordService.trainningPublish(condition);
        return ResultBean.success("");
    }
    @ApiOperation(value = "培训活动统计列表")
    @GetMapping("trainingStatistics")
    public Object trainingStatistics(SearchEduTrainningRecord condition) {
        return eduTrainningRecordService.trainingStatistics(condition);
    }
    @ApiOperation(value = "签到记录导出")
    @GetMapping("exportSignIn")
    public void exportSignIn(@RequestParam Long id, HttpServletResponse response) {
        eduTrainningRecordService.exportSignIn(id,response);
    }

    @ApiOperation(value = "培训学员统计")
    @GetMapping("studentStatistics")
    public Object studentStatistics(SearchEduTrainningRecord condition) {
       return eduTrainningRecordService.studentStatistics(condition);
    }

    @ApiOperation(value = "导出培训学员统计")
    @GetMapping("exportStudentStatistics")
    public void exportStudentStatistics(SearchEduTrainningRecord condition,HttpServletResponse response) {
        eduTrainningRecordService.exportStudentStatistics(condition,response);
    }
    @ApiOperation(value = "批量录入培训结果")
    @PostMapping("saveTrainingResult")
    public Object saveTrainingResult(@RequestBody SearchEduTrainningRecord condition) {
        return eduTrainningRecordService.saveTrainingResult(condition);
    }

    @ApiOperation(value = "二维码校验")
    @GetMapping("qrCodeValid")
    public Object qrCodeValid(@RequestParam Long id) {
        return eduTrainningRecordService.qrCodeValid(id);
    }

    @ApiOperation(value = "app我的培训活动-全部")
    @GetMapping("myTrainingList")
    public Object myTrainingList(SearchEduTrainningRecord condition) {
        return eduTrainningRecordService.myTrainingList(condition);
    }
    @ApiOperation(value = "app我的培训活动-详情")
    @GetMapping("myTrainingDetails")
    public Object myTrainingDetails(@RequestParam Long trainingId) {
        return eduTrainningRecordService.myTrainingDetails(trainingId);
    }

    // @RequiresPermissions("edu:trainning:record")
    @RequestMapping("join-in-user-list")
    public Object getJoinInUserList(@Valid @NotNull(field = "id") Long id) {
        List<EduTrainningRecordUserDetailBean> list = eduTrainningRecordService.findJoinInUsersById(id);
        return ResultBean.success(list);
    }

    // @RequiresPermissions("edu:trainning:record")
    @RequestMapping("certRecord")
    public Object certRecord(@Valid @NotNull(field = "id") Long id) {
        List<EduTrainningRecordUserDetailBean> list = eduTrainningRecordService.certRecord(id);
        return ResultBean.success(list);
    }

    //  @RequiresPermissions("edu:trainning:record")
    @RequestMapping("award-cert")
    public Object awardCert(@RequestBody List<EduTrainningRecordUserDetailBean> awards) {
        eduTrainningRecordService.awardUserCerts(awards);
        return ResultBean.success(null);
    }

    @GetMapping("web-user-info-train")
    @ApiOperation(value = "web端个人信息查询-培训记录, userContractorFlag: 0 人员; 1 承包商人员", response = EduTrainUserInfoDto.class)
    public ResultBean userInfoTrain(Long userId, Pageable pageable, Integer userContractorFlag) {
        return eduTrainningRecordService.userInfoTrain(userId, pageable, userContractorFlag);
    }

    /**
     * 培训记录详情（app）
     * @param trainingRecordId
     * @return
     */
    @GetMapping("detail")
    @ApiOperation(value = "培训记录详情（app）")
    @RequestMapping("findDetail")
    public Object detail(@RequestParam("trainingRecordId") Long trainingRecordId) {
        return ResultBean.success(eduTrainningRecordService.findDetail(trainingRecordId));
    }

    @PostMapping("importExcelData")
    @ApiOperation("培训记录结果导入")
    public ResultBean importExcel(MultipartFile file) {
        List<String> meaages = null;
        try {
            meaages = eduTrainningRecordService.importExcelData(file);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultBean.fail(101, "导入失败");
        }
        return ResultBean.success(meaages);
    }

    @PostMapping("importTrainningRecord")
    @ApiOperation("培训记录导入")
    public ResultBean importTrainningRecord(MultipartFile file) {
        if (!file.getOriginalFilename().endsWith("xlsx") && !file.getOriginalFilename().endsWith("xls")) {
            return ResultBean.success(Lists.newArrayList("文件类型不正确"));
        }
        try {
            List<String> errorMessage = eduTrainningRecordService.importTrainningRecord(file);
            return ResultBean.success(errorMessage);
        } catch (Exception e) {
            return ResultBean.success(Lists.newArrayList("导入失败:" + e.getMessage()));
        }
    }

    @GetMapping("oldData")
    @ApiOperation(value = "处理老数据")
    public Object oldData() {
        eduTrainningRecordService.oldData();
        return ResultBean.success("");
    }

}
